package wechat

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"strings"
)

// 微信公众号菜单
type Menu struct {
	Button []*OneLevelMenu `json:"button"`
}

type OneLevelMenu struct {
	Type      string          `json:"type,omitempty"`
	Name      string          `json:"name"`
	Key       string          `json:"key,omitempty"`
	Url       string          `json:"url,omitempty"`
	SubButton []*TwoLevelMenu `json:"sub_button,omitempty"`
}

type TwoLevelMenu struct {
	Type string `json:"type"`
	Name string `json:"name"`
	Url  string `json:"url,omitempty"`
	Key  string `json:"key,omitempty"`
}

type MenuRes struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

func (m *Menu) Create(key string) {
	menuJson, err := json.Marshal(m)
	if err != nil {
		logs.Info("can not marshal wechat menu struct", err)
		return
	}
	accessToken := GetAccessToken(key)
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", accessToken)
	req, _ := http.NewRequest("POST", url, strings.NewReader(string(menuJson)))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Do(req)
	if err != nil {
		logs.Error("send wechat create menu request fail:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error("can not read from wechat template message response:", err)
		return
	}
	var menuRes MenuRes
	err = json.Unmarshal(body, &menuRes)
	if err != nil {
		logs.Error("can not unmarshal wechat create menu response response:", err)
		return
	}
	if menuRes.Errcode != 0 {
		logs.Error("wechat create menu fail:", menuRes.Errmsg)
		return
	}
}
